/******************************************************************************
 * 
 *Taylor Chan's works,just for practice!
 * 
 *****************************************************************************/

package com.cq.thinkinjava.concurrent.cancelthread;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 *nio的io中断
 * 
 * @author Taylor Chan
 * @since 1.0
 * @version 2012-7-25 Taylor Chan Creat
 */
public class NIOInterruption {
    
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        ServerSocket server = null;
        try {
            server = new ServerSocket(8080);
        } catch (IOException e) {
            // TODO 自动生成异常捕获块存根注释，块实现时请删除此注释
            e.printStackTrace();
        }
        InetSocketAddress isa = new InetSocketAddress("localhost", 8080);
        SocketChannel sc1 = null;
        SocketChannel sc2 = null;
        try {
            sc1 = SocketChannel.open(isa);
            sc2 = SocketChannel.open(isa);
        } catch (IOException e) {
            // TODO 自动生成异常捕获块存根注释，块实现时请删除此注释
            e.printStackTrace();
        }
        Future<?> f = exec.submit(new NIOBlocked(sc1));
        exec.execute(new NIOBlocked(sc2));
        exec.shutdown();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            // TODO 自动生成异常捕获块存根注释，块实现时请删除此注释
            e.printStackTrace();
        }
        f.cancel(true);
        try {
            sc2.close();
        } catch (IOException e) {
            // TODO 自动生成异常捕获块存根注释，块实现时请删除此注释
            e.printStackTrace();
        }
    }
}

class NIOBlocked implements Runnable {
    
    private final SocketChannel sc;
    
    /**
     * 
     */
    public NIOBlocked(SocketChannel sc) {
        this.sc = sc;
    }
    
    /**
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        System.out.println("waiting for read() in " + this);
        try {
            sc.read(ByteBuffer.allocate(1));
        } catch (ClosedByInterruptException e) {
            System.out.println(this + " is interrupted!");
        } catch (IOException e) {
            // TODO 自动生成异常捕获块存根注释，块实现时请删除此注释
            e.printStackTrace();
        }
        System.out.println("Exiting NIOBlocked.run() " + this);
    }
    
}
